package com.github.baichuan.application.scaffold.rest.domain.organization;

import com.github.baichuan.application.scaffold.rest.domain.application.Application;
import com.github.baichuan.application.scaffold.rest.domain.application.ApplicationService;
import com.github.baichuan.application.scaffold.rest.dto.org.OrgForm;
import com.github.baichuan.application.scaffold.rest.dto.tenant.TenantForm;
import com.github.baichuan.application.scaffold.rest.jpa.organization.OrgRepository;
import com.github.baichuan.application.scaffold.rest.jpa.organization.TenantRepository;
import com.github.baichuan.utils.SnowFlake;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.web.error.NoSuchEntityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class TenantService {
    @Autowired
    private TenantRepository tenantRepository;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    private OrgService orgService;
    @Autowired
    private SnowFlake snowFlake;

    public Tenant find(String id){
        return tenantRepository.findById(id).orElseThrow(() -> new NoSuchEntityException("租户不存在"));
    }

    public Page<Tenant> query(Specification<Tenant> specification, Pageable pageable){
        return tenantRepository.findAll(specification, pageable);
    }

    public Result add(String applicationCode, TenantForm form){
        Application application = applicationService.findByCode(applicationCode);

        if(application.getTenant() == Application.TenantMode.SINGLE) {
            return Result.fail("应用平台当前为单租户模式，无法创建租户");
        }

        if(tenantRepository.find(application, form.getName()).isPresent()){
            return Result.fail("租户名称重复");
        }

        if(orgRepository.find(application, null, form.getName()).isPresent()){
            return Result.fail("租户机构名称重复");
        }

        Tenant tenant = new Tenant();
        tenant.setId(snowFlake.nextBase62Id().substring(2));
        tenant.setApplication(application);
        tenant.setName(form.getName().trim());
        tenantRepository.save(tenant);

        // 为租户创建同名机构
        orgService.add(application, tenant);

        return Result.success("租户添加成功", tenant.getId());
    }

    public Result edit(String id, String applicationCode, TenantForm form){
        Tenant tenant = find(id);

        if(!tenant.getApplication().getCode().equals(applicationCode)){
            return Result.fail("权限不足");
        }

        tenant.setName(form.getName());
        tenantRepository.save(tenant);

        return Result.success("租户保存成功");
    }
}
